/* eslint-disable no-undef */
//app.js
import config from "./config";
import { login, info } from "./utils/api/user";
import { wxLogin, wxShowMaskLoading } from "./utils/promisify";
import weekOfYear from "./utils/dayjs/plugin/weekOfYear";
import dayjs from "./utils/dayjs/dayjs.min";
dayjs.extend(weekOfYear);
App({
    globalData: {
        userInfo: null,
        token: null,
    },
    /**
     * 登陆获取值
     */
    login() {
        return new Promise((resolve, reject) => {
            wx.getUserInfo({
                success: (res) => {
                    wxLogin().then(({ code }) => {
                        let _login = {
                            code: code,
                            rawData: res.rawData,
                        };
                        login(_login).then((e) => {
                            if (!e.code) {
                                wx.hideLoading();
                                wx.showToast({
                                    title: "登陆失败",
                                    duration: 2000,
                                    image: "",
                                });
                                reject(e.msg);
                                return;
                            } else {
                                let token = e.data.userInfo.token;
                                this.globalData.token = token;
                                wx.setStorage({ key: "token", data: token });
                                resolve(token);
                            }
                        });
                    });
                },
            });
        });
    },
    /**
     * 获取用户信息/上课时间/周数
     */
    getInfo() {
        return new Promise((resolve) => {
            info().then((v) => {
                this.globalData.userInfo = v.data;
                this.classTime(v.data.class_time);
                this.weeksList(v.data.first_term_start,v.data.second_term_start);
                if (this.userInfoReadyCallback) {
                    this.userInfoReadyCallback(v.data);
                }
                resolve(v.data);
                wx.hideLoading();
            });
        });
    },
    /**
     * 获取用户信息
     */
    getSet() {
        return new Promise((resolve) => {
            wx.getSetting({
                success: (res) => {
                    if (res.authSetting["scope.userInfo"]) {
                        // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
                        this.globalData.token = wx.getStorageSync("token");
                        if (!this.globalData.token) {
                            // 获取用户上课时间
                            this.login().then((v) => {
                                console.log(v, "v");
                                this.getInfo();
                            });
                        } else {
                            wx.checkSession({
                                success: () => {
                                    //session_key 未过期，并且在本生命周期一直有效
                                    resolve(this.getInfo());
                                },
                                fail: () => {
                                    //session_key 过期
                                    this.login();
                                },
                            });
                        }
                    } else {
                        wx.hideLoading();
                    }
                },
            });
        });
    },
    /**
     * 上课时间
     */
    classTime(times) {
        var checkdate = function (t1, t2) {
            var t11 = t1.split(":");
            var t21 = t2.split(":");
            var sj1 = parseInt(t11[0] * 12 + t11[1]);
            var sj2 = parseInt(t21[0] * 12 + t21[1]);
            return sj1 > sj2 ? false : true;
        };
        let _times = JSON.parse(times).map((v) => {
            if (checkdate("12:00", v.s_time)) {
                v.pm = true;
            }
            return v;
        });
        wx.setStorage({ key: "classTime", data: _times });
    },
  /**
   * 生成当前周的日期列表
   */
   weeksList(start, second) {
    if (!start) {
      return;
    }
    let first_term_start = dayjs(`${dayjs().format('YYYY')}-${start}`).format('YYYY-MM-DD'); // 第一学期开始周时间
    let second_term_start = dayjs(`${dayjs().format('YYYY')}-${second}`).format('YYYY-MM-DD'); // 第二学期开始周时间
    let _firstStartWeek = dayjs(first_term_start).week(); // 第一学期开始周为当年第几周
    let _secondStartWeek = dayjs(second_term_start).week(); // 第二学期开始周为当年第几周
    let _tdWeek = dayjs().week(); // 今天为当年第几周
    if (_tdWeek < _secondStartWeek) {
      // 1月份到3月份
      let _ly = dayjs().subtract(1, 'year');
      let _lyWeek = dayjs(_ly).isoWeeksInYear(); // 去年总共周数
      wx.setStorage({
        key: 'currentWeek',
        data: _tdWeek + _lyWeek - _firstStartWeek + 1
      });
    } else if (_tdWeek < _firstStartWeek) {
      // 9月份以前
      wx.setStorage({
        key: 'currentWeek',
        data: _tdWeek - _secondStartWeek + 1
      });
    } else {
      // 9月份后
      wx.setStorage({
        key: 'currentWeek',
        data: _tdWeek - _firstStartWeek + 1
      });
    }
  },
    onShow() {
        this.getSet();
    },
    onLaunch: function () {
        wxShowMaskLoading("登陆中");
        // 获取用户信息
        this.getSet();
        // 获取系统状态栏信息
        wx.getSystemInfo({
            success: (e) => {
                this.globalData.StatusBar = e.statusBarHeight;
                let capsule = wx.getMenuButtonBoundingClientRect();
                if (capsule) {
                    this.globalData.displayArea = {
                        windowHeight: e.windowHeight,
                        windowWidth: e.windowWidth,
                        screenHeight: e.screenHeight,
                    };
                    this.globalData.Custom = capsule;
                    this.globalData.CustomBar =
                        capsule.bottom + capsule.top - e.statusBarHeight;
                } else {
                    this.globalData.CustomBar = e.statusBarHeight + 50;
                }
            },
        });
        this.globalData.ImgUrl = config.server.img.baseUrl;
    },
});
